﻿using CeremonyBackground.Infrastructure;
using CeremonyBackground.Models;
using CeremonyBackground.ViewModel;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace CeremonyBackground.Tasks
{
    /// <summary>
    /// 同步博饼记录服务
    /// </summary>
    public class BobingSyncPrizeService
    : BackgroundService
    {
        private readonly BackgroundTasksDbContext _context;
        private readonly CSRedis.CSRedisClient _redisClient;
        private readonly BackgroundTaskSettings _settings;
        private readonly ILogger<BobingSyncPrizeService> _logger;
        public BobingSyncPrizeService(ILogger<BobingSyncPrizeService> logger,
            BackgroundTasksDbContext context,
            IOptionsSnapshot<BackgroundTaskSettings> settings)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _context = context ?? throw new ArgumentException(nameof(context));
            _settings = settings.Value ?? throw new ArgumentNullException(nameof(settings));
            if (_redisClient == null)
            {
                _redisClient = new CSRedis.CSRedisClient(_settings.RedisTaskConnectionString);
                RedisHelper.Initialization(_redisClient);
            }
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await Task.Run(async() => await Process(stoppingToken));
        }
        protected async Task Process(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    var prizeResult = RedisHelper.BLPop<SyncPrizeResult>(10, _settings.BobingPrizeTaskName);
                    if (prizeResult == null)
                        continue;
                    var dbUser = _context.BobingUsers.FirstOrDefault(t => t.AuthorizationCode == prizeResult.AuthorizationCode);
                    //新增
                    if (dbUser != null)
                    {
                        await _context.BobingPrizeResults.AddAsync(new BobingPrizeResult(dbUser.Id, prizeResult.PrizeId, prizeResult.PrizeResult));
                        int result = await _context.SaveChangesAsync();
                        string resultStr = result > 0 ? "成功" : "失败";
                        _logger.LogInformation("----- Sync BobingPrizeResults {Result}: {BobingPrizeResults}: ({@BobingPrizeResults})",
                                 resultStr,
                                 prizeResult.GetType().Name,
                                 prizeResult);
                    }
                    else
                    {
                        _logger.LogInformation($"----- 同步博饼记录失败:授权码:{prizeResult.AuthorizationCode}不存在");
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                }
            }
        }
    }
}
